﻿<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HostFormCommon.ascx.cs" Inherits="Sagacity.NC.Form.HostFormCommon" %>
<%@ Register Assembly="Coolite.Ext.Web" Namespace="Coolite.Ext.Web" TagPrefix="ext" %>

<script type="text/javascript" language="javascript" src="../../resources/JS/Sg.js"  defer="defer"></script>

<script type="text/javascript" language="javascript" src="../../resources/JS/examples.js"  defer="defer"></script>

<!--基本操作-->
<script language="javascript" type="text/javascript" defer="defer">
    var  selectedKeyId = 0;
    var xmlDoc = null;
    function GetXMLDoc(){
        if(xmlDoc != null)
          return;
        xmlDoc = Sg.xmlDocument();
        if(xmlDoc != null)
          xmlDoc.loadXML(<%=hidXML.ClientID %>.getValue());
    }
      
    function excuteSave(){
        GetXMLDoc();
        
        ///调用保存前执行事件
        if(typeof beforeExcuteEvent != "undefined"){
            if(!eval(beforeExcuteEvent))
                return;
         }
        
        if(!FormValidate()){
           Ext.Msg.alert('注意','保存时数据验证失败，请检查你的数据。');
           return;
        }
        if(xmlDoc != null){
          var editFields = xmlDoc.selectNodes("Root/Fields/Field[@EnableEdit='True']");
          for(var i =0;i < editFields.length;i++){
            var type = editFields[i].attributes[1].text;
            var getvalue = editFields[i].attributes[0].text;
            var controlName = "<%=this.ClientID %>_"+getvalue;
            var obj = null;
            
            try{
               obj =  eval(controlName);
            }catch(e){
                continue;
            }
            
            switch(type){
              case "DateTime":
                    var date = obj.getValue();
                    if(date == ""){
                        editFields[i].attributes[5].text = "";
                    }else{
                        editFields[i].attributes[5].text = toDate(date);
                    }                            
                    break;
              case "Month":
              case "Text":
                   editFields[i].attributes[5].text = obj.getValue();
                   break;
              case "TextArea":
                   editFields[i].attributes[5].text = obj.getValue();
                   break;
              case "Numeric":
                   editFields[i].attributes[5].text = obj.value;
                   if(eval("<%=this.ClientID %>_"+getvalue).getValue() == ""){
                      editFields[i].attributes[5].text = "0";
                   }
                  break;
              case "Tree":
                  //已在getTreeSelectValue()中处理
                  break;
                  
              case "PositionSelector":
                    break;
              case "PersonSelector":
                    break;
              case "":
                    break;
              default:
                   editFields[i].attributes[5].text = obj.value;
                   break;
            }
          }
          
              var exState= <%=hidExcuteState.ClientID %>.getValue();
              xmlDoc.selectSingleNode("Root/TableInfo").attributes[1].text = exState;
              <%=hidXML.ClientID %>.setValue(xmlDoc.xml);
          
              Coolite.AjaxMethods.<%=this.ClientID %>.SubmitForm({success:function(result){ 
              
                  selectedKeyId=<%=hidSelect.ClientID %>.getValue().split("$")[0];                
                   if(result){
                       //保存成功后执行的方法
                       if(typeof successSavedEvent != 'undefined')
                            eval(successSavedEvent);
 
                      /*--------新增成功后,重定向页面数据并且要刷新当前页面的父级页面显示出当前添加或者修改的数据--------*/
                      if((typeof showRedirection != "undefined")&&(exState==0)){              
                          eval(showRedirection);
                      }
                      /*------当删除成功后执行页面清空-------*/
                      if((typeof DelRedirection != "undefined") &&(exState==2))
                      {
                         eval(DelRedirection);
                      }
                   }
              },
              eventMask: {
                  showMask: true,
                  msg: '正在执行...'
              }});
          }
    }

    //----------针对树形选择器-------------//
    var partText = "";
    var selectNode = null;
    function showTreeWin(window){
        eval("<%=this.ClientID %>_"+window).show();
    }
    
    function Form$isDataType(node,btnName){
         var enable = node.attributes.dataType == 0;
         eval("<%=this.ClientID %>_"+btnName).setDisabled(enable);
    }    

    function hideTreeWin(window){
      eval("<%=this.ClientID %>_"+window).hide();
    }
      
    function getTreeSelectValue(trigger,tree,window){
        GetXMLDoc();
        var node = eval("<%=this.ClientID %>_"+tree).getSelectionModel().selNode;
        selectNode = node;
        if(node != null && node != "undefined")
        {
            hideTreeWin(window);
            eval("<%=this.ClientID %>_"+trigger).setValue(node.text);
            var e = xmlDoc.selectSingleNode("Root/Fields/Field[@EnableEdit='True'][@ControlType='Tree'][@Name='"+trigger+"']");
            if(e != null)
                e.attributes[5].text = node.id;
        }
        else
            alert("请选择一个节点。");
    }
    //-------------------------------------//

    function FormValidate(){
        var editFields = xmlDoc.selectNodes("Root/Fields/Field[@EnableEdit='True']");
        var validate = true;
        for(var i = 0 ;i < editFields.length;i++){
            var controlName = "<%=this.ClientID %>_"+editFields[i].attributes[0].text;
            try{
                if(!eval(controlName).validate())
                {
                    validate = false;
                    break;
                }
            }catch(e){}
        }
        return validate;
     }
     
     var ShowWindow = function()
     {
         var key = <%=hidSelect.ClientID %>.getValue().split("$")[0];
         var resourceId =<%=hidResourceId.ClientID %>.getValue();
         <%=winLogForm.ClientID %>.show();
         <%=winLogForm.ClientID %>.autoLoad.url = "../../sys/Log/LogDetail.aspx?resourceId="+resourceId+"&keyId="+key;
         <%=winLogForm.ClientID %> .autoLoad.nocache = true;
         <%=winLogForm.ClientID %>.reload();
     }
     
     /*--新增数据--*/
     function NewData(orgId){
        
        //showFunctionAdd方法由调用此用户控件的页面提供
        if(typeof showFunctionAdd != 'undefined' )
        {
            eval(showFunctionAdd);
            return;
        }
        document.getElementById('<%=hidParentValue.ClientID %>').value =orgId;
        

        <%=hidExcuteState.ClientID %>.setValue(0);
        
//         Coolite.AjaxMethods.<%=this.ClientID %>.GetCodeXML({success:function(result){ 
//         if(<%=hidCode.ClientID %>.getValue()==""){
//             Ext.Msg.alert('注意','本级编码规则未定义！');
//             return;
//          }else {clearForm(); return;}}});

        clearForm();
        <%=btnSave.ClientID %>.setDisabled(false);
     }
       /*--将窗体表单中的控件的值清空（用于新增）--*/
      function clearForm(){
        GetXMLDoc();
        if(xmlDoc != null){
       var strparent= document.getElementById('<%=hidParentValue.ClientID %>').value;
        if(strparent != undefined){
        var strPare=strparent.split('$');
        var addFields = xmlDoc.selectNodes("Root/Fields/Field[@Name='"+strPare["0"]+"']");
        if(addFields!=undefined)
        { 
             for(var j=0; j<addFields.length;j++)
                     addFields[j].attributes[5].value= strPare[1];
            
        }
        }
          var editFields = xmlDoc.selectNodes("Root/Fields/Field[@EnableEdit='True']");
          for(var i =0;i < editFields.length;i++){
           var field = editFields[i].attributes[0].text;
            var type = editFields[i].attributes[1].text;
            var getvalue = editFields[i].attributes[0].text;
            switch(type){
              case "Tree":
                  eval("<%=this.ClientID %>_"+getvalue).setValue("");
                  var e = xmlDoc.selectSingleNode("Root/Fields/Field[@EnableEdit='True'][@ControlType='Tree'][@Name='"+field+"']");
                  if(e != null)
                   e.attributes[5].text = "";
                  break;
                   case "Text":
                     var codeName = <%=hidCodeName.ClientID %>.getValue();
                    var code = <%=hidCode.ClientID %>.getValue();
                  if(getvalue == codeName)
                   eval("<%=this.ClientID %>_"+getvalue).setValue(code);
                  else
                   eval("<%=this.ClientID %>_"+getvalue).setValue("");
                  break;
              case "Button":
                  break;
              default:
                  eval("<%=this.ClientID %>_"+getvalue).setValue("");
                  break;
            }
          }
        }
      }
      
      
       //删除数据
     function DelData(){
    
      var selects = <%=hidSelect.ClientID %>.getValue();    
      if(selects == 0){
        Ext.Msg.alert('注意','请选择需要操作的数据。');
        return;
      }
         Ext.MessageBox.confirm('注意', '确认是否删除？', function(btn) {
                    if (btn=="yes") {          
            <%=hidExcuteState.ClientID %>.setValue(2);
            excuteSave();
            
            }
        });
       
     }

    //<!--Ajax加载树-->

    function Form$nodeLoad(node) {
        Coolite.AjaxMethods.<%=this.ID %>.NodeLoad(node.id,node.attributes.fieldId,node.attributes.nodeClickHandler, {
            success: function(result) {
                var data = eval("(" + result + ")");
                node.loadNodes(data);
            },

            failure: function(errorMsg) {
                Ext.Msg.alert('节点加载失败', errorMsg);
            }
        });            
    }
    
    function triggerValue(fieldName,index,otherEvent){
         if(index == 0){            
             GetXMLDoc();
             var field = xmlDoc.selectSingleNode("Root/Fields/Field[@EnableEdit='True'][@Name='"+fieldName+"']");
             eval("<%=this.ClientID %>_"+fieldName+".setValue('')");
             field.attributes[5].text = '';
         }else{
            eval(otherEvent);
         }
     }
</script>

<!--选择器执行-->
<script type="text/javascript" language="javascript">
    function Form$GetSelectorValue(type,fieldName){
        GetXMLDoc();
        var reValue = window.showModalDialog("../Form/Selector.aspx?type="+type,
            '',"dialogWidth:700px;dialogHeight:380px;scroll:no;status:no;toolbar:no;menubar:no;resizable:no;");
            
        if(reValue == null || reValue == 'undefined')
            return;
            
        var temps = reValue.split(";")[0].split("$");
        var e = xmlDoc.selectSingleNode("Root/Fields/Field[@EnableEdit='True'][@Name='"+fieldName+"']");
        eval("<%=this.ClientID %>_"+fieldName+".setValue('"+temps[1]+"')");
        e.attributes[5].text = temps[0];
    }
</script>

<!--公式设计器-->
<script language="javascript" type="text/javascript"  defer="defer" >
    var Form$FormulaFns = null;
    //显示公式设计器
    function showFormulaDesigner(fieldName){
        if(Form$FormulaFns == null){
            Ext.Msg.alert("注意","标志名称为空，不能进行进一步的设置。");
            return;
        }
        
        for(var i = 0;i < Form$FormulaFns.length ;i ++){
            if(fieldName == Form$FormulaFns[i]["FieldName"]){
                eval(Form$FormulaFns[i]["FnName"]);
                break;
            }
        }
    }
</script>

<!--执行SQL方案-->
<script language="javascript" type="text/javascript">
    function excuteSqlCases(){
        var exsqlcases = "";
        var sqlcases = document.getElementById('<%=hidSqlCases.ClientID %>').value.split(',');
        for(var i = 0 ;i < sqlcases.length;i++){
            var temp = eval("<%=this.ClientID %>_ckSqlCase"+sqlcases[i]);
            if(temp.checked){
                exsqlcases += sqlcases[i]+",";
            }   
        }
        
        Coolite.AjaxMethods.<%=this.ClientID %>.ExcuteSqlCases(exsqlcases,{
            success:function(result){
                if(result == ""){
                    Ext.Msg.alert("注意","方案执行成功！");
                }else{
                    Ext.Msg.alert("注意",result);
                }
            },failure:function(msg){
                Ext.Msg.alert(msg);
            },eventMask: {
                  showMask: true,
                  msg: '正在执行...'
           },timeout:60000
        });
    }
</script>

<!--附件管理器-->
<script language="javascript" type="text/javascript">
    function filesAttachment(){
        var objId = <%=hidSelect.ClientID %>.getValue().replace("$","");
        if(objId == "0"){
            Ext.Msg.alert("注意","请先保存新增数据！");
            return;
        }
        var reValue = window.showModalDialog("../form/ResourceAttachment.aspx?ResourceId=<%=ResourceId %>&ObjId="+objId,
        "","dialogWidth:590px;dialogHeight:380px;scroll:no;status:yes;toolbar:no;menubar:no;resizable:yes;");
    }
</script>

<!--样式设置-->
<script language="javascript" type="text/javascript" defer="defer">
    window.onresize = function(){
        resetFormSize();
    }
    
    window.onload = function(){
        document.body.attachEvent("onmouseover",function(){resetFormSize();});
    }
    
    function resetFormSize(){
        var bodywidth = document.body.clientWidth;
        var bodyheight = document.body.clientHeight;
        var pnlForm = document.getElementById("<%=this.ClientID %>_pnlForm");
        var wvalue =document.getElementById('<%=HidWidthValue.ClientID %>').value;
        var str ;
        if(wvalue==1){
            str = bodywidth - 280;
        }else{
            str = bodywidth - 23;
        }
        
        try{
            pnlForm.style.width = str;
            pnlForm.style.height = bodyheight - 23;
        }catch(e){} 
    }
</script>

<!--设置关联字段信息-->
<script language="javascript" type="text/javascript" >
    var cbStores = new Array();
    
    //取得关联字段的值
    function getAssoFieldValues(Name){
        GetXMLDoc();
        
        var assoField = xmlDoc.selectSingleNode("Root/Fields/Field[@Name='"+Name+"'][@AssoParam]");
        var assoInfo = eval(assoField.getAttribute("AssoParam"));
        var selectedValue = "";
        if(assoField.getAttribute("ControlType") == "Tree")
            selectedValue = assoField.getAttribute("Value");
        else if(assoField.getAttribute("ControlType") == "Combox")
            selectedValue = eval('<%=this.ClientID %>_'+ Name).getValue();
        
        for(var i = 0; i < assoInfo.length ;i++){
            var fieldId = assoInfo[i]["FieldId"];
            var fieldName = assoInfo[i]["FieldName"];
            var paramName =  assoInfo[i]["ParamName"];
            
            var field = xmlDoc.selectSingleNode("Root/Fields/Field[@EnableEdit='True'][@Name='"+fieldName+"']");
            var controlType = field.getAttribute("ControlType");            
            
            Coolite.AjaxMethods.<%=this.ClientID %>.GetFieldAssoDataInfo(controlType,fieldId,paramName,selectedValue,{
                success:function(result){
                    SetAssoFieldValue(result);
                },
                failure:function(errormsg){
                    Ext.Msg.alert("注意",errormsg);
                }
            });
        }
    }
    
    //设置关联字段控件值
    function SetAssoFieldValue(values){    
        var results = values.split("$");
        values = eval(results[0]);
        var orgData = eval("[{"+results[1]+"}]")[0];
        controlType = orgData.controlType;
        var fieldName = orgData.fieldName;
        control = controlType == "Combox" ? eval('<%=this.ClientID %>_'+ fieldName) : eval('<%=this.ClientID %>_Tree_'+ fieldName);
        
        if(controlType == "Tree"){
            eval('<%=this.ClientID %>_'+ fieldName).enable();
            eval('<%=this.ClientID %>_'+ fieldName).setReadOnly(false);
            if(control.root.loaded == false){
                control.root.rootVisible = false;
            }
            control.root.loaded = true;
            control.root.removeChildren();
            appendChild(values,control.root,fieldName);
        }else if(controlType == "Combox"){
            
            /*-----------------保存重设前的Combox的数据，以便重设---------------------*/
            var hasRecored = false;
            for(var i = 0;i< cbStores.length;i++){
                if(cbStores[0].FieldName == fieldName){
                    hasRecored = true;
                }
            }
            
            if(!hasRecored){
                var store = new Object();
                store.FieldName = fieldName;
                store.items = control.getStore().data.items;
                cbStores[cbStores.length] = store;
            }
            /*----------------------*/
            
            control.enable();
            control.getStore().removeAll();
            control.setValue('');
            
            for(var i = 0 ;i < values.length;i++){                
                control.addItem(values[i]["CAPTION"],values[i]["ID"]);
            }
        }
    }
    
      function appendChild(data,node,fieldName){
          for(var i = 0;i < data.length ;i++){ 
             var showChecked = typeof data[i].CHECKED != 'undefined';
             var checked = data[i].CHECKED == "true";
             
             var n = null;
             
             //当前节点的IsData属性值是否为true，判断是否生成树控件节点的checkbox
             if(showChecked)
                n = new Ext.tree.TreeNode({
                    id:data[i].ID,
                    checked:checked,
                    text:data[i].CAPTION
                });
             else
                n = new Ext.tree.TreeNode({
                    id:data[i].ID,
                    text:data[i].CAPTION,
                    dataType:data[i].ISDATA,
                    listeners:{
                        "click":function(node,event){
                            Form$isDataType(this,fieldName);
                        }
                    }
                });
                
             node.appendChild(n);
             appendChild(data[i]["CHILDREN"],n,fieldName);
          }
       }
       
       function restoreComboxData(){
            for(var i = 0 ;i < cbStores.length;i++){
                var control = eval('<%=this.ClientID %>_'+ cbStores[i].FieldName);
                control.getStore().removeAll();
                control.disable();
                for(var j =0;j < cbStores[i].items.length;j++){  
                    var value = cbStores[i].items[j].data;                  
                    control.addItem(value.text,value.value);                    
                }
            }
       }
</script>

<style type="text/css">
    .panelcss
    {
        padding-left: 20px;
        font-size: 9pt;
        position:relative;
        overflow-y:scroll;
    }
</style>

<asp:HiddenField ID="hidKey" runat="server" />
<ext:Hidden ID="hidXML" runat="server" />
<ext:Hidden ID="hidExcuteState" runat="server" />
<ext:Hidden ID="hidSelect" runat="server" />
<ext:Hidden ID="hidResourceId" runat="server" />
<asp:HiddenField ID="hidParentValue" runat="server" />
<asp:HiddenField ID="hidSqlCases" runat="server" />
<ext:Hidden ID="hidCode" runat="server" />
<ext:Hidden ID="hidCodeName" runat="server" />
<asp:HiddenField ID="HidWidthValue" runat="server" Value="0" />
<ext:BorderLayout ID="BorderLayout1" runat="server">
    <Center>
        <ext:Panel ID="panel1" runat="server" BodyStyle="position:fixed;" AutoScroll="true" Header="false">
            <Body>
                <ext:Toolbar ID="projectToolbar" Visible="true" runat="server">
                    <Items>
                        <ext:ToolbarButton ID="btnSave" runat="server" Visible="false" Icon="Disk" Text="保 存">
                            <Listeners>
                                <Click Handler="javascript:excuteSave();" />
                            </Listeners>
                        </ext:ToolbarButton>
                        <ext:ToolbarButton ID="btnRefresh" runat="server" Icon="ArrowRotateAnticlockwise"
                            Text="刷 新">
                            <Listeners>
                                <Click Handler="javascript:window.location.reload();" />
                            </Listeners>
                        </ext:ToolbarButton>
                        <ext:ToolbarButton ID="btnAsso" runat="server" Visible="true" Text="关联操作" Icon="LinkEdit">
                            <Menu>
                                <ext:Menu ID="RowContextMenu" runat="server">
                                    <Items>
                                        <ext:MenuItem ID="MenuLogInfo" runat="server" Enabled="true" Visible="true" Icon="UserAlert"
                                            Text="日志信息">
                                            <Listeners>
                                                <Click Handler="javascript:ShowWindow();" />
                                            </Listeners>
                                        </ext:MenuItem>
                                        <ext:MenuItem ID="MenuSelfUpdate" Text="自动更新" Visible="true" AllowDomMove="true"
                                            runat="server" Icon="TableGo">
                                            <Listeners>
                                                <Click Handler="#{winSqlForm}.show();" />
                                            </Listeners>
                                        </ext:MenuItem>
                                        <ext:MenuItem ID="MenuDataSel" Text="数据检查" Visible="true" AllowDomMove="true" runat="server"
                                            Icon="DatabaseGear">
                                        </ext:MenuItem>
                                        <ext:MenuItem ID="MenuAttachment" Text="附件管理" Visible="true" Icon="Film" AllowDomMove="true" runat="server">
                                            <Listeners>
                                                <Click Handler="javascript:filesAttachment();" />
                                            </Listeners>                                                                             
                                        </ext:MenuItem>
                                        <ext:MenuItem ID="MenuBizInfo" Text="业务单关联信息" Visible="true" Icon="Bin" runat="server" AllowDomMove="true">
                                        </ext:MenuItem>
                                        
                                    </Items>
                                </ext:Menu>
                            </Menu>
                        </ext:ToolbarButton>
                    </Items>
                </ext:Toolbar>
                <asp:Panel ID="pnlForm" CssClass="panelcss" Height="420" Width="890" runat="server">     
                        
                </asp:Panel>
            </Body>
        </ext:Panel>
    </Center>
</ext:BorderLayout>

<ext:Window ID="winLogForm" ShowOnLoad="false" Maximizable="true" Title="日志信息" Icon="Wand"
    Modal="true" runat="server" Height="250" Width="700">
    <AutoLoad Url="" Mode="IFrame">
    </AutoLoad>
    <Listeners>
        <Activate Handler="#{winLogForm}.maximize();" />
    </Listeners>
</ext:Window>

<ext:Window ID="winSqlForm" ShowOnLoad="false" Title="SQL执行方案" Resizable="false" ButtonAlign="Center" Maximizable="false" runat="server" Width="500">
    <Body>
    <table style="width:100%;">
        <tr>
            <td style="width:100%;" colspan="2">
            <table id="tbSqlCase" runat="server">            
        </table>
            </td>
        </tr>
        <tr>
            <td align="right">
                <ext:Button ID="btnSqlExcute" runat="server" Icon="HtmlGo"  Text="执 行">
                    <Listeners>
                        <Click Handler="excuteSqlCases();#{winSqlForm}.hide();" />
                    </Listeners>
                </ext:Button>
            </td>
            <td>
                <ext:Button ID="btnCancelSql" runat="server" Icon="Cancel" Text="取 消">
                    <Listeners>
                        <Click Handler="#{winSqlForm}.hide();" />
                    </Listeners>    
                </ext:Button>
            </td>
        </tr>
    </table>
    </Body>
</ext:Window>

<asp:Panel ID="otherContent" runat="server">
</asp:Panel>
